package com.stress.testing.plugin.java.jdbc.wrapper;

import com.stress.testing.common.conf.AgentConfig;
import com.stress.testing.common.conf.PluginConfig;
import com.stress.testing.plugin.java.jdbc.sql.util.SQLParserUtils;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

import static com.stress.testing.common.conf.PluginConfigKey.PLUGIN_JAVA_JDBC_DBTYPE_KEY;

public class ConnectionWrapper implements Connection {
    private final static String DATABASE_TYPE_UNKNOW = "UNKNOW";
    private Connection target;
    private AgentConfig agentConfig;
    private PluginConfig pluginConfig;
    private String url;
    private String databaseType;

    public ConnectionWrapper(Connection target, String url, AgentConfig agentConfig, PluginConfig pluginConfig) {
        this.target = target;
        this.url = url;
        this.agentConfig = agentConfig;
        this.pluginConfig = pluginConfig;
        this.databaseType = resolveDatabaseType(url, pluginConfig);
    }

    private String resolveDatabaseType(String url, PluginConfig pluginConfig) {
        String dbtypePair = pluginConfig.get(PLUGIN_JAVA_JDBC_DBTYPE_KEY, null);
        if (dbtypePair == null || dbtypePair.length() == 0) {
            return DATABASE_TYPE_UNKNOW;
        }

        String[] pairs = dbtypePair.split(";");
        if (pairs == null || pairs.length == 0) {
            return DATABASE_TYPE_UNKNOW;
        }

        for (String pair : pairs) {
            if (pair == null || pair.length() == 0) {
                continue;
            }

            String[] kv = pair.split(",");
            if (kv == null || kv.length != 2) {
                continue;
            }

            if (url.startsWith(kv[1])) {
                return kv[0];
            }
        }

        return DATABASE_TYPE_UNKNOW;
    }

    @Override
    public Statement createStatement() throws SQLException {
        return new StatementWrapper(target.createStatement(), agentConfig, pluginConfig, databaseType);
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareStatement(newSql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareCall(newSql);
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.nativeSQL(newSql);
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        target.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return target.getAutoCommit();
    }

    @Override
    public void commit() throws SQLException {
        target.commit();
    }

    @Override
    public void rollback() throws SQLException {
        target.rollback();
    }

    @Override
    public void close() throws SQLException {
        target.close();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return target.isClosed();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return target.getMetaData();
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        target.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return target.isReadOnly();
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {
        target.setCatalog(catalog);
    }

    @Override
    public String getCatalog() throws SQLException {
        return target.getCatalog();
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {
        target.setTransactionIsolation(level);
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return target.getTransactionIsolation();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return target.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException {
        target.clearWarnings();
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return target.createStatement(resultSetType, resultSetConcurrency);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareStatement(newSql, resultSetType, resultSetConcurrency);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareCall(newSql, resultSetType, resultSetConcurrency);
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return target.getTypeMap();
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
        target.setTypeMap(map);
    }

    @Override
    public void setHoldability(int holdability) throws SQLException {
        target.setHoldability(holdability);
    }

    @Override
    public int getHoldability() throws SQLException {
        return target.getHoldability();
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return target.setSavepoint();
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return target.setSavepoint(name);
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {
        target.rollback(savepoint);
    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
        target.releaseSavepoint(savepoint);
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return target.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareStatement(newSql, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareCall(newSql, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareStatement(newSql, autoGeneratedKeys);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareStatement(newSql, columnIndexes);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        String newSql = SQLParserUtils.changeTableName(sql, agentConfig, pluginConfig, databaseType);
        return target.prepareStatement(newSql, columnNames);
    }

    @Override
    public Clob createClob() throws SQLException {
        return target.createClob();
    }

    @Override
    public Blob createBlob() throws SQLException {
        return target.createBlob();
    }

    @Override
    public NClob createNClob() throws SQLException {
        return target.createNClob();
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return target.createSQLXML();
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return target.isValid(timeout);
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        target.setClientInfo(name, value);
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        target.setClientInfo(properties);
    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return target.getClientInfo(name);
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return target.getClientInfo();
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return target.createArrayOf(typeName, elements);
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return target.createStruct(typeName, attributes);
    }

    @Override
    public void setSchema(String schema) throws SQLException {
        target.setSchema(schema);
    }

    @Override
    public String getSchema() throws SQLException {
        return target.getSchema();
    }

    @Override
    public void abort(Executor executor) throws SQLException {
        target.abort(executor);
    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
        target.setNetworkTimeout(executor, milliseconds);
    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return target.getNetworkTimeout();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return target.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return target.isWrapperFor(iface);
    }
}
